package cn.lds.j375.chlm.controller;

import cn.lds.j375.chlm.dto.ResultDTO;
import cn.lds.j375.chlm.entity.User;
import cn.lds.j375.chlm.exception.ChlmException;
import cn.lds.j375.chlm.serivce.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    private Logger log = LoggerFactory.getLogger(UserController.class);

    @RequestMapping("/login")
    public String login(HttpSession session,Model model){

        if (null != session.getAttribute("loginUser")){
            model.addAttribute("msg","您已登录，请注销后切换用户");
            return "home";
        }


        return "login";
    }

    /**
     * 用户登录  如果登录成功，重定向到首页 否则转发回登录页面
     * @param user
     * @param model
     * @param session
     * @return
     */
    @RequestMapping(value = "do_login",method = RequestMethod.POST)
    public String doLogin(User user, Model model, HttpSession session){

        ResultDTO<User> userResultDTO = userService.loginUser(user);

        if (userResultDTO.getCode().equals(4000)){
            model.addAttribute("err",userResultDTO.getMsg());
            return "login";
        }
        //登录用户放入session
        session.setAttribute("loginUser",userResultDTO.getObj());

        return "redirect:/";

    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){

        session.removeAttribute("loginUser");

        return "home";
    }

    @RequestMapping("/reg")
    public String reg(){
        return "reg";
    }

    @RequestMapping("/do_reg")
    public String doReg(User user) throws ChlmException {
        log.info("regUser:{}",user);
        userService.regUser(user);
        return "login";
    }

    @ResponseBody
    @RequestMapping("/check_user")
    public ResultDTO checkUser(@RequestBody User user){

        ResultDTO<List<User>> listResultDTO = userService.selectUserAll(user);

        return listResultDTO;
    }


}
